<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>成本数据导入 - 模态窗口</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-white">
    <div class="p-6">
        <form id="costImportForm" class="space-y-4">
            <!-- 数据表名称 -->
            <div>
                <label for="cost-table-name" class="block text-sm font-medium text-gray-700 mb-1">
                    成本数据表名称 <span class="text-red-500">*</span>
                </label>
                <select id="cost-table-name" required
                        class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    <option value="">请选择成本数据表</option>
                </select>
            </div>

            <!-- 平台选择 -->
            <div>
                <label for="cost-platform" class="block text-sm font-medium text-gray-700 mb-1">
                    平台
                </label>
                <select id="cost-platform"
                        class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    <option value="">请选择平台（可选）</option>
                </select>
            </div>

            <!-- 店铺选择 -->
            <div>
                <label for="cost-store" class="block text-sm font-medium text-gray-700 mb-1">
                    店铺
                </label>
                <select id="cost-store"
                        class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    <option value="">请先选择平台（可选）</option>
                </select>
            </div>

            <!-- 时间范围 -->
            <div class="grid grid-cols-2 gap-3">
                <div>
                    <label for="cost-start-date" class="block text-sm font-medium text-gray-700 mb-1">
                        开始时间 <span class="text-red-500">*</span>
                    </label>
                    <input type="date" id="cost-start-date" required
                           class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                </div>
                <div>
                    <label for="cost-end-date" class="block text-sm font-medium text-gray-700 mb-1">
                        结束时间 <span class="text-red-500">*</span>
                    </label>
                    <input type="date" id="cost-end-date" required
                           class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                </div>
            </div>

            <!-- 导入规则 -->
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">导入规则（聚水潭中间表请选更新）</label>
                <select id="cost-import-rule" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-sm">
                    <option value="">请选择导入规则</option>
                </select>
            </div>

            <!-- 进度条 -->
            <div id="cost-import-progress" class="hidden">
                <div class="bg-gray-200 rounded-full h-1.5">
                    <div id="cost-progress-bar" class="bg-green-600 h-1.5 rounded-full transition-all duration-300" style="width: 0%"></div>
                </div>
                <p id="cost-progress-text" class="text-xs text-gray-600 mt-1 text-center">0%</p>
            </div>

            <!-- 按钮区域 -->
            <div class="flex justify-center space-x-4 pt-6 border-t">
                <button type="button" onclick="window.parent.closeCostModal()"
                        class="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors text-sm">
                    取消
                </button>
                <button type="submit" id="cost-submit-btn"
                        class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors disabled:opacity-50 text-sm">
                    开始导入成本数据
                </button>
            </div>
        </form>
    </div>

    <script>
        // 导入规则常量
        const COST_IMPORT_RULES = {
            APPEND: 'append',
            OVERWRITE: 'overwrite',
            UPDATE: 'update'
        };

        // 加载导入规则
        async function loadCostImportRules() {
            try {
                const response = await fetch('/api/operate-types');
                const rules = await response.json();

                const ruleSelect = document.getElementById('cost-import-rule');
                ruleSelect.innerHTML = '<option value="">请选择导入规则</option>';

                rules.forEach(rule => {
                    const option = document.createElement('option');
                    option.value = rule.id;
                    option.textContent = rule.name;
                    ruleSelect.appendChild(option);
                });

                // 默认选择第一个选项（追加数据）
                if (rules.length > 0) {
                    ruleSelect.selectedIndex = 1; // 跳过"请选择导入规则"选项
                }
            } catch (error) {
                console.error('加载导入规则失败:', error);
                alert('加载导入规则失败，请刷新页面重试');
            }
        }

        // 加载成本数据表数据
        async function loadCostTableNames() {
            try {
                const response = await fetch('/api/tablesofcost');
                const tables = await response.json();

                const tableSelect = document.getElementById('cost-table-name');

                tableSelect.innerHTML = '<option value="">请选择成本数据表</option>';

                tables.forEach(table => {
                    const option = document.createElement('option');
                    const value = table.table_name || table.table || table.name || '';
                    option.value = value;
                    option.textContent = table.name || table.table_name || value;
                    tableSelect.appendChild(option);
                });

            } catch (error) {
                console.error('加载成本数据表数据失败:', error);
                alert('加载成本数据表数据失败，请刷新页面重试');
            }
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', () => {
            loadCostPlatforms();
            loadCostTableNames();
            loadCostImportRules();
            setCostDefaultDates();
        });

        // 设置默认日期
        function setCostDefaultDates() {
            const today = new Date();
            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);

            document.getElementById('cost-end-date').value = today.toISOString().split('T')[0];
            document.getElementById('cost-start-date').value = yesterday.toISOString().split('T')[0];
        }

        // 加载平台数据
        async function loadCostPlatforms() {
            try {
                const response = await fetch('/api/platforms');
                const platforms = await response.json();

                const platformSelect = document.getElementById('cost-platform');
                platformSelect.innerHTML = '<option value="">请选择平台（可选）</option>';

                platforms.forEach(platform => {
                    const option = document.createElement('option');
                    option.value = platform.plat_id;
                    option.textContent = platform.plat_name;
                    platformSelect.appendChild(option);
                });

                // 绑定平台变化事件
                platformSelect.addEventListener('change', handleCostPlatformChange);

            } catch (error) {
                console.error('加载平台数据失败:', error);
                alert('加载平台数据失败，请刷新页面重试');
            }
        }

        // 处理平台选择变化
        async function handleCostPlatformChange(event) {
            const selectedPlatform = event.target.value;
            const storeSelect = document.getElementById('cost-store');

            if (selectedPlatform) {
                try {
                    const response = await fetch(`/api/stores/${encodeURIComponent(selectedPlatform)}`);
                    const stores = await response.json();

                    storeSelect.innerHTML = '<option value="">请选择店铺（可选）</option>';
                    stores.forEach(store => {
                        const option = document.createElement('option');
                        option.value = store.shop_id;
                        option.textContent = store.shop_name;
                        storeSelect.appendChild(option);
                    });
                } catch (error) {
                    console.error('加载店铺数据失败:', error);
                    storeSelect.innerHTML = '<option value="">加载失败</option>';
                }
            } else {
                storeSelect.innerHTML = '<option value="">请先选择平台（可选）</option>';
            }
        }

        // 表单提交处理
        document.getElementById('costImportForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const submitBtn = document.getElementById('cost-submit-btn');
            const progressDiv = document.getElementById('cost-import-progress');
            const progressBar = document.getElementById('cost-progress-bar');
            const progressText = document.getElementById('cost-progress-text');

            // 获取表单数据
            const tableName = document.getElementById('cost-table-name').value;
            const platform = document.getElementById('cost-platform').value;
            const store = document.getElementById('cost-store').value;
            const startDate = document.getElementById('cost-start-date').value;
            const endDate = document.getElementById('cost-end-date').value;
            const operateType = document.getElementById('cost-import-rule').value;

            // JS校验
            if (!tableName) {
                alert('请选择成本数据表名称');
                return;
            }
            if (!startDate) {
                alert('请选择开始时间');
                return;
            }
            if (!endDate) {
                alert('请选择结束时间');
                return;
            }
            if (!operateType) {
                alert('请选择导入规则');
                return;
            }

            // 获取显示名称
            const tableDisplayName = document.getElementById('cost-table-name').selectedOptions[0]?.textContent || tableName;
            const platformDisplayName = document.getElementById('cost-platform').selectedOptions[0]?.textContent || platform;
            const storeDisplayName = document.getElementById('cost-store').selectedOptions[0]?.textContent || (store ? '已选择' : '未选择');
            const operateTypeDisplayName = document.getElementById('cost-import-rule').selectedOptions[0]?.textContent || operateType;

            // 确认提示
            const confirmMessage = `请确认成本数据导入信息：
            \n数据表：${tableDisplayName}
            \n平台：${platformDisplayName}   店铺：${storeDisplayName}
            \n导入规则：${operateTypeDisplayName}
            \n开始时间：${startDate} 结束时间：${endDate}
            \n确定要开始导入成本数据吗？`;

            if (!confirm(confirmMessage)) {
                return;
            }

            // 显示进度条
            submitBtn.disabled = true;
            progressDiv.classList.remove('hidden');

            try {
                // 获取当前选中的账套信息
                let selectedAccount = '';
                if (window.parent && window.parent.document) {
                    const accountSelect = window.parent.document.getElementById('account-select');
                    if (accountSelect && accountSelect.selectedOptions && accountSelect.selectedOptions[0]) {
                        const selectedOption = accountSelect.selectedOptions[0];
                        const id = selectedOption.value; // 获取账套ID
                        const name = selectedOption.textContent; // 获取账套名称
                        const acctID = selectedOption.getAttribute('data-id') || ''; // 获取acctID
                        selectedAccount = `${id},${name},${acctID}`; // 按格式拼接
                    }
                }

                // 准备保存数据
                const saveData = {
                    table_name: tableName,
                    plat_id: platform || '',// 可以为空
                    shop_id: store || '',  // 可以为空
                    start_time: startDate,
                    end_time: endDate,
                    operate_type: operateType,
                    remark: selectedAccount  // 将账套信息保存到remark字段
                };

                // 调用后端API保存成本任务
                const response = await fetch('/api/save-task', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(saveData)
                });

                const result = await response.json();

                if (result.success) {
                    alert('成本数据导入任务创建成功！');

                    // 关闭模态框并重新加载任务列表
                    if (window.parent && window.parent.closeCostModal) {
                        window.parent.closeCostModal();
                        // 重新加载任务列表
                        if (window.parent && window.parent.loadTasks) {
                            window.parent.loadTasks();
                        }
                    }
                } else {
                    alert(`成本数据导入任务创建失败：${result.message}`);
                    submitBtn.disabled = false;
                    progressDiv.classList.add('hidden');
                }
            } catch (error) {
                alert(`成本数据导入任务创建失败：${error.message}`);
                submitBtn.disabled = false;
                progressDiv.classList.add('hidden');
            }
        });

        // 模拟进度更新（实际使用时应该根据后端API的进度反馈来更新）
        function updateCostProgress(percent) {
            const progressBar = document.getElementById('cost-progress-bar');
            const progressText = document.getElementById('cost-progress-text');

            progressBar.style.width = `${percent}%`;
            progressText.textContent = `${percent}%`;
        }
    </script>
</body>
</html>